package core.ste;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import core.annotation.Annotation.Process;

public class SteController {
	Log log = LogFactory.getLog(this.getClass());
	private static final Map<String, Method> methods = new HashMap<String, Method>();
	private boolean initedMethods = false;

	@Process
	public void list() {
		System.out.println("list");
	}

	public void exec(String methoName) throws RuntimeException {
		if (!initedMethods) {
			init();
		}
		Method m = methods.get(methoName);
		if (m != null) {
			try {
				m.invoke(this, null);
			} catch (IllegalAccessException e) {
				log.error(e);
				throw new RuntimeException(e);
			} catch (InvocationTargetException e) {
				log.error(e);
				throw new RuntimeException(e);

			}
		} else {
			log.error(String.format("can not find method:%s", methoName));
		}
	}

	private void init() {
		synchronized (this) {
			if (!initedMethods) {
				initedMethods = true;
				for (Method m : this.getClass().getMethods()) {
					Process p = m.getAnnotation(Process.class);
					if (p != null) {
						methods.put(m.getName().toLowerCase(), m);
					}
				}
			}
		}
	}
}
